/*
Copyright (c) 2008 Mark Rickert

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

import com.google.maps.LatLng;
import com.google.maps.MapType;
import com.google.maps.controls.*;
import com.google.maps.overlays.Marker;
import com.google.maps.services.Directions;
import com.google.maps.services.DirectionsEvent;
import com.mileage_tracker.util.*;

import flash.events.Event;
import flash.filesystem.*;
import flash.net.URLRequest;

import mx.controls.Alert;
import mx.events.CloseEvent;

[Bindable] private var _data_provider:Array = new Array();
[Bindable] private var _is_networked:Boolean = false;
[Bindable] private var _total_miles:uint = 0;

private var _the_distance:Number; 
private var _documents_directory:File = File.documentsDirectory;
private var _ical_events:Array = new Array();
private var _csv_events:Array = new Array();
private var _home_address:String;
private var _search_words:Array;
private var _adding:Number = 0;
private var _all_events:Object = new Object();

private function add_events_async():void
{
	for(var i:String in _all_events)
	{
		query_add_mileage.parameters = [_all_events[i].start_date + "", _all_events[i].title + "\n" + _all_events[i].description, _home_address, "", null, 1];
		query_add_mileage.execute();	
	}
	
	list_miles();
	
	mileage_grid.selectedIndex = -1;
	address_to.text = "";
	mileage.text = "";
	address_to.setFocus();
	query_add_mileage.parameters = new Array();	
}

private function add_mileage_log():void
{	
	query_add_mileage.addEventListener(SQLEvent.RESULT, function():void
	{
		list_miles();

		mileage_grid.selectedIndex = -1;
		address_to.text = "";
		address_to.setFocus();
		mileage.text = "";
		query_add_mileage.parameters = new Array();
	});
		query_add_mileage.parameters = [date.text, trip_description.text, address_from.text, address_to.text, mileage.text, round_trip.selected];
		query_add_mileage.execute();
}

private function alert_message(message:String):void
{
	var a:Alert = Alert.show(
		message, 
		"Alert");
}

// Initialize the application
public function application_creation_complete():void
{
	restore_window_location();
	NativeApplication.nativeApplication.addEventListener(Event.NETWORK_CHANGE, check_network_connection);
	check_network_connection();
}

private function confirm_delete_selected_mileage_log(event:CloseEvent):void
{
	switch(event.detail)
	{
		case Alert.YES:
			var idx:Number = mileage_grid.selectedIndex;
			query_delete_mileage.parameters = [mileage_grid.selectedItem.id];
			query_delete_mileage.addEventListener(SQLEvent.RESULT, function():void
			{
				list_miles();
			});

			query_delete_mileage.execute();
			break;
		case Alert.NO:
			break;
	}
}

private function directions_mileage_found(event:DirectionsEvent):void {
	var dir:Directions = event.directions;
	var zoom:uint = this.map.getBoundsZoomLevel(dir.bounds);
	this.map.setZoom(zoom);
	this.map.setCenter(dir.bounds.getCenter());
	this.map.clearOverlays();
	this.map.addOverlay(dir.createPolyline());

	var startLatLng:LatLng = dir.getRoute(0).getStep(0).latLng;
	var endLatLng:LatLng = dir.getRoute(dir.numRoutes-1).endLatLng;		
	this.map.addOverlay(new Marker(startLatLng));
	this.map.addOverlay(new Marker(endLatLng));

	_the_distance = (dir.distance / 1609.344);
	mileage.text = _the_distance.toFixed(2).toString();
}

private function directions_mileage_not_found(event:DirectionsEvent):void {
  // Process failure, perhaps by showing an alert
  trace("Finding directions failed.");
 
 	var a:Alert = Alert.show(
		"Your destination address couldn't be found. Would you like to open a browser to see if Google has a suggestion?", 
		"Error", 
		Alert.YES|Alert.NO, 
		this, 
		open_google_for_suggestions, 
		null, 
		Alert.NO);
}

private function directions_found(event:DirectionsEvent):void {
	var dir:Directions = event.directions;
	var zoom:uint = this.map.getBoundsZoomLevel(dir.bounds);
	this.map.setZoom(zoom);
	this.map.setCenter(dir.bounds.getCenter());
	this.map.clearOverlays();
	this.map.addOverlay(dir.createPolyline());
}

private function directions_not_found(event:DirectionsEvent):void {
  // Process failure, perhaps by showing an alert
  trace("Directions Failed: " + event);
}

private function exportCSVFile():void
{
	var desktopDir:File = File.desktopDirectory;
	try
	{
	    desktopDir.browseForSave("Save As");
	    desktopDir.addEventListener(Event.SELECT, exportCSVFile_save);
	}
	catch (error:Error)
	{
	    trace("Failed:", error.message);
	}
}

private function exportCSVFile_save(event:Event):void
{
    var newFile:File = event.target as File;
    
    //Grab the info to write to the file:
    var str:String = "\"Date\",\"Trip Description\",\"From Address\",\"To Address\",\"Total Mileage\"";
    for(var i:Number = 0;i<mileage_grid.dataProvider.length;i++)
    {
    	//trace(mileage_grid.dataProvider[i]);
    	str = str + "\n\"" + removeQuotes(mileage_grid.dataProvider[i].date) + "\",";
    	str = str + "\"" + removeQuotes(mileage_grid.dataProvider[i].trip_description) + "\",";
    	str = str + "\"" + removeQuotes(mileage_grid.dataProvider[i].address_from) + "\",";
    	str = str + "\"" + removeQuotes(mileage_grid.dataProvider[i].address_to) + "\",";
    	str = str + "\"" + removeQuotes(mileage_grid.dataProvider[i].total_mileage) + "\"";
    }

    var stream:FileStream = new FileStream();
    stream.open(newFile, FileMode.WRITE);
    stream.writeUTFBytes(str);
    stream.close();
}

private function filter_clear_list():void
{
	filter_list.text = "";
	filter_the_list();
}

private function list_miles(evt:SQLEvent=null):void 
{	
	query_list_mileage.addEventListener(SQLEvent.RESULT, function():void
	{
		_data_provider = query_list_mileage.data;
		_total_miles = sum(array_mileage_column(_data_provider));
		filter_the_list();
	});
	_data_provider = new Array();
	query_list_mileage.data = null;
	query_list_mileage.execute();
}

private function mileage_update_event(event:Event):void
{
	trace("event: " + event + " - " + typeof event);
	//data_provider[];
}

// Do this when the map is loaded and ready
private function map_ready(event:Event):void
{
	this.map.setCenter(new LatLng(39.5,-98.5), 3, MapType.NORMAL_MAP_TYPE);
	this.map.addControl(new MapTypeControl());
	this.map.addControl(new PositionControl());
	this.map.addControl(new ZoomControl());
	
	mileage_grid.enabled = true;
}
		
private function mileage_log_new():void
{
	mileage_grid.selectedIndex = -1;
	address_to.text = "";
	mileage.text = "";
	address_to.setFocus();
	filter_list.text = "";
}

private function mileage_log_update():void
{	
	var select_me_again:uint = mileage_grid.selectedIndex;
	
	query_update_mileage.addEventListener(SQLEvent.RESULT, function():void
	{
		list_miles();

		mileage_grid.selectedIndex = select_me_again;
		mileage_grid.scrollToIndex(select_me_again);
		address_to.text = "";
		mileage.text = "";
		address_to.setFocus();
		query_add_mileage.parameters = new Array();
	});
		query_update_mileage.parameters = [date.text, trip_description.text, address_from.text, address_to.text, mileage.text, round_trip.selected, mileage_grid.selectedItem.id];
		query_update_mileage.execute();
}

private function mileage_log_delete():void
{
	var a:Alert = Alert.show(
		"Are you sure you want to delete this mileage log?", 
		"Confirm", 
		Alert.YES|Alert.NO, 
		this, 
		confirm_delete_selected_mileage_log, 
		null, 
		Alert.NO);
}

private function mileage_find():void
{
	var dir:Directions = new Directions();
	dir.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, directions_mileage_found);
	dir.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, directions_mileage_not_found);
	dir.load(address_from.text + " to " + address_to.text);
}

private function new_mileage(e:Event):void
{
	_data_provider.push(e.target.data);
}

private function open_google_for_suggestions(event:CloseEvent):void
{
	switch(event.detail)
	{
		case Alert.YES:
			var request:URLRequest = new URLRequest('http://maps.google.com/maps?q='+address_to.text);
			navigateToURL(request);
			break;
		case Alert.NO:
			break;
	}   
}

private function removeQuotes(str:String):String
{
	return str.split("\"").join();	
}


private function show_directions():void
{
	// Create a directions object
	var dir:Directions = new Directions();
	dir.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, directions_found);
	dir.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, directions_not_found);
	dir.load(mileage_grid.selectedItem.address_from + " to " + mileage_grid.selectedItem.address_to);
}

private function save_address_from():void
{
	LocalStore.saveToStore("fromAddress", address_from.text);
}

private function mileage_save():void
{
	if(address_from.text.length <= 0)
	{
		alert_message("Please fill out the from address.");
	}
	else if(address_to.text.length <= 0)
	{
		alert_message("Please fill out the to address.");
	}
	else if(date.text.length <= 0)
	{
		alert_message("Please select a date.");
	}
	else if(mileage.text.length <= 0)
	{
		alert_message("Please fill out the mileage.");
	}
	else
	{
		// Everything is filled out. Proceed!
		if(mileage_grid.selectedIndex != -1)mileage_log_update();
		else add_mileage_log();
	}
}

private function sum(a:Array):Number
{
	var j:Number = 0;
	for(var i:String in a)
	{
		j += a[i];
	}
	return j;
}

private function array_mileage_column(a:Array):Array
{
	var ret:Array = new Array();
	for(var i:String in a)
	{
		ret[i] = a[i].total_mileage;
	}			
	return ret;	
}

private function restore_window_location():void
{
	var posX:int = WindowPrefs.getInt('main.window.x');
	var posY:int = WindowPrefs.getInt('main.window.y');
	var posWidth:int = WindowPrefs.getInt('main.window.width');
	var posHeight:int = WindowPrefs.getInt('main.window.height');
	move(posX, posY);
	if(posWidth)this.width = posWidth;
	if(posHeight)this.height = posHeight;
}

private function check_network_connection(event:Event=null):void
{
	var headRequest:URLRequest = new URLRequest();
	headRequest.method = "HEAD";
	headRequest.url = "http://www.google.com";	
	var connectTest:URLLoader = new URLLoader(headRequest);
	connectTest.addEventListener(HTTPStatusEvent.HTTP_STATUS, connectHttpStatusHandler);
	connectTest.addEventListener(Event.COMPLETE, connectCompleteHandler);
	connectTest.addEventListener(IOErrorEvent.IO_ERROR, connectErrorHandler);  
}

private function connectHttpStatusHandler(event:*=null):void
{
	if (event.status == "0" ? _is_networked = false:_is_networked = true);
}			

private function connectErrorHandler(event:IOErrorEvent):void
{
	_is_networked = false;
	Alert.show("You do not currently have a network connection");
}

private function connectCompleteHandler(event:Event):void
{
	_is_networked = true;
}

private function selectiCalFile():void
{
	if(address_from.text == "")
	{
		alert_message("Please fill out the 'from' address that you want inserted for all these records.");
	}
	else
	{
		_home_address = address_from.text;
		var filters:Array = new Array();
		filters.push( new FileFilter( 'iCal Files', '*.ics' ) );
		
		_documents_directory.addEventListener( Event.SELECT, doSelectiCalFile );
		_documents_directory.browseForOpen( 'Select iCal File', filters );
	}
}

private function selectCSVFile():void
{
	if(address_from.text == "")
	{
		alert_message("Please fill out the 'from' address that you want inserted for all these records.");
	}
	else
	{
		_home_address = address_from.text;
		var filters:Array = new Array();
		filters.push( new FileFilter( 'CSV Files', '*.txt;*.csv' ) );
		
		_documents_directory.addEventListener( Event.SELECT, doSelectCSVFile );
		_documents_directory.browseForOpen( 'Select CSV File', filters );
	}
}

private function doSelectiCalFile(e:Event):void
{
	trace(_documents_directory.nativePath);
    var f:File = File.applicationDirectory.resolvePath(_documents_directory.nativePath);
	
    var fs:FileStream = new FileStream();
    fs.open(f, FileMode.READ);
    var content:String = fs.readUTFBytes(fs.bytesAvailable);
    fs.close();
    _ical_events = xmlICALLoaded(content);

	trace("Total Events Found: " + _ical_events.length);
	_all_events = _ical_events;
	add_events_async();
}

private function doSelectCSVFile(e:Event):void
{
	trace(_documents_directory.nativePath);
    var f:File = File.applicationDirectory.resolvePath(_documents_directory.nativePath);
	
    var fs:FileStream = new FileStream();
    fs.open(f, FileMode.READ);
    var content:String = fs.readUTFBytes(fs.bytesAvailable);
    fs.close();
    _csv_events = parseCSV(content);

	trace("Total Events Found: " + _ical_events.length);
	_all_events = _csv_events;
	add_events_async();
}

private function xmlICALLoaded(content:String):Array {
	
	// ICAL Data variables
	var dat:String = content as String;
	var split:Array = dat.split("\r\n").split("\n").split("\r");
	
	// Variables used in looping
	var VEVENT:Boolean = false;
	var _title:String;
	var _sDate:String;
	var _eDate:String;
	var _where:String;
	var _description:String;
	
	var events:Array = new Array();
	
	for (var j:int=0; j<split.length; j++) {
		// Have we gotten to an event? Or ended one?
		if (split[j] == "BEGIN:VEVENT") {
			VEVENT = true;
			
			_title = "";
			_where = "";
			_description = "";
		} else if (split[j] == "END:VEVENT") {
			VEVENT = false;

			events.push({'title':_title, 'start_date':_sDate, 'end_date':_eDate, 'description':_description, 'location':_where});
		}
		
		// If inside an EVENT, we can start extracting data
		if (VEVENT) {
			if (split[j].indexOf("DTSTART") != -1) {
				_sDate = createICALDate( split[j] );
			} else if (split[j].indexOf("DTEND") != -1) {
				_eDate = createICALDate( split[j] );
			} else if (split[j].indexOf("LOCATION") != -1) {
				_where = split[j].slice(9, split[j].length);
				//trace(_where);
			} else if (split[j].indexOf("DESCRIPTION") != -1) {
				//Check the next lines to see if there is a space as the first element
				var _addtlLines:Number = 0;
				while(split[j + _addtlLines + 1].charAt(0) == " ")
				{
					_addtlLines++;	
				}
				
				_description = split[j].slice(12, split[j].length);
				for(var i:uint = 0; i<_addtlLines;i++)
				{
					_description += split[j + i + 1];
				}
				
				_description = _description.split('\\,').join(",");
				_description = _description.split('\\ ,').join(",");
				_description = _description.split('\\n').join("\n");
				_description = _description.split('\\ n').join("\n");
				_description = _description.split('\\"').join("\"");
				_description = _description.split('\\ "').join("\"");
				//trace(_where);
			} else if (split[j].indexOf("SUMMARY") != -1) {
				_title = split[j].slice(8, split[j].length);
				_title = _title.split('\\,').join(",");
				_title = _title.split('\\ ,').join(",");
				_title = _title.split('\\n').join("\n");
				_title = _title.split('\\ n').join("\n");
				_title = _title.split('\\"').join("\"");
				_title = _title.split('\\ "').join("\"");
				//trace(_title);
			}
		}
		
	}
	
	return events;
}

private function createICALDate(s:String):String {
	var date:String = s.slice(s.indexOf(":")+1, s.length);
	var monthString:String;
	var month:Number;
	var dayString:String;
	
	if (date.indexOf("T") == -1) { // simple date
		var simpleDate:Date = new Date( date.slice(0, 4), int(date.slice(4, 6))-1, date.slice(6, 8) );
		
		month = simpleDate.month + 1;
		if(month < 10)monthString = "0" + month;
		else monthString = month + "";
		
		if(simpleDate.date < 10)dayString = "0" + simpleDate.date;
		else dayString = simpleDate.date + "";
		
		return simpleDate.fullYear + "-" + monthString + "-" + dayString;
	} else {
		var extDate:Date = new Date( date.slice(0, 4), int(date.slice(4, 6))-1, date.slice(6, 8), date.slice(9, 11), date.slice(11, 13), date.slice(13, 15) );

		month = extDate.month + 1;
		if(month < 10)monthString = "0" + month;
		else monthString = month + "";

		if(extDate.date < 10)dayString = "0" + extDate.date;
		else dayString = extDate.date + "";
		
		return extDate.fullYear + "-" + monthString + "-" + dayString;
	}
}

private function parseCSV(str:String):Array
{
	var csvArray:Array = str.split("\r\n").split("\n").split("\r");
	for(var i:Number = 0;i<csvArray.length;i++)
	{
		csvArray[i] = csvArray[i].split(",");
		for(var j:Number = 0;j<csvArray[i].length;j++)
		{
			csvArray[i][j] = removeQuotes(csvArray[i][j]);
		}
	}
	return csvArray;
}

private function filter_the_list():void
{
	_search_words = filter_list.text.split(" ");
	
	if(filter_list.text.length == 0 && filter_miles.selected == false)
	{
		mileage_grid.dataProvider.filterFunction = null;
	}
	else
	{
		if(mileage_grid.dataProvider.filterFunction == null)
		{
			mileage_grid.dataProvider.filterFunction = filter_process;
		}
	}
	mileage_grid.dataProvider.refresh();
}

private function filter_process(item:Object):Boolean
{
	for ( var i:String in _search_words) 
	{
		if(filter_miles.selected == true && item.total_mileage != "" && item.total_mileage > 0)return false;
		if(item.trip_description.toLowerCase().indexOf(_search_words[i].toLowerCase()) == -1)return false;
	}
	return true;
}